<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tetris Game - 构建监控面板</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }
        
        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }
        
        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: transform 0.2s;
        }
        
        .card:hover {
            transform: translateY(-2px);
        }
        
        .card h3 {
            color: #4a5568;
            margin-bottom: 15px;
            font-size: 1.2rem;
        }
        
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .status-success { background-color: #48bb78; }
        .status-failed { background-color: #f56565; }
        .status-building { background-color: #ed8936; animation: pulse 2s infinite; }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        .build-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .build-item:last-child {
            border-bottom: none;
        }
        
        .build-info {
            flex: 1;
        }
        
        .build-commit {
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 4px;
        }
        
        .build-meta {
            font-size: 0.9rem;
            color: #718096;
        }
        
        .build-duration {
            font-weight: 600;
            color: #4a5568;
        }
        
        .quick-actions {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            transition: all 0.2s;
        }
        
        .btn-primary {
            background: #4299e1;
            color: white;
        }
        
        .btn-primary:hover {
            background: #3182ce;
        }
        
        .btn-secondary {
            background: #e2e8f0;
            color: #4a5568;
        }
        
        .btn-secondary:hover {
            background: #cbd5e0;
        }
        
        .metrics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .metric-card {
            background: #f7fafc;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }
        
        .metric-value {
            font-size: 2rem;
            font-weight: bold;
            color: #2d3748;
        }
        
        .metric-label {
            font-size: 0.9rem;
            color: #718096;
            margin-top: 5px;
        }
        
        .chart-container {
            position: relative;
            height: 300px;
            margin-top: 20px;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #718096;
        }
        
        .error {
            background: #fed7d7;
            color: #c53030;
            padding: 15px;
            border-radius: 6px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎮 Tetris Game</h1>
            <p>企业级构建监控面板 - 实时监控构建状态与性能指标</p>
        </div>
        
        <div class="dashboard-grid">
            <!-- 当前状态卡片 -->
            <div class="card">
                <h3>🚀 当前状态</h3>
                <div id="current-status" class="loading">加载中...</div>
                <div class="quick-actions">
                    <a href="http://onepiececrush.cn" class="btn btn-primary" target="_blank">访问应用</a>
                    <a href="http://82.157.51.127:2122" class="btn btn-secondary" target="_blank">Jpom管理</a>
                </div>
            </div>
            
            <!-- 构建统计 -->
            <div class="card">
                <h3>📊 构建统计</h3>
                <div class="metrics-grid">
                    <div class="metric-card">
                        <div class="metric-value" id="total-builds">-</div>
                        <div class="metric-label">总构建次数</div>
                    </div>
                    <div class="metric-card">
                        <div class="metric-value" id="success-rate">-</div>
                        <div class="metric-label">成功率</div>
                    </div>
                </div>
                <div class="chart-container">
                    <canvas id="statusChart"></canvas>
                </div>
            </div>
            
            <!-- 最近构建 -->
            <div class="card">
                <h3>📝 最近构建</h3>
                <div id="recent-builds" class="loading">加载中...</div>
            </div>
            
            <!-- 系统监控 -->
            <div class="card">
                <h3>🖥️ 系统监控</h3>
                <div class="quick-actions">
                    <a href="http://82.157.51.127:9090" class="btn btn-secondary" target="_blank">Prometheus</a>
                    <a href="http://82.157.51.127:3001" class="btn btn-secondary" target="_blank">Grafana</a>
                </div>
                <div class="metrics-grid">
                    <div class="metric-card">
                        <div class="metric-value" id="system-cpu">-</div>
                        <div class="metric-label">CPU使用率</div>
                    </div>
                    <div class="metric-card">
                        <div class="metric-value" id="system-memory">-</div>
                        <div class="metric-label">内存使用率</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let statusChart = null;
        
        // 获取构建数据
        async function fetchBuildData() {
            try {
                const response = await fetch('/api/builds');
                if (!response.ok) throw new Error('Failed to fetch build data');
                return await response.json();
            } catch (error) {
                console.error('Error fetching build data:', error);
                return null;
            }
        }
        
        // 更新当前状态
        function updateCurrentStatus(data) {
            const statusDiv = document.getElementById('current-status');
            
            if (!data || !data.recent_builds || data.recent_builds.length === 0) {
                statusDiv.innerHTML = '<div class="error">暂无构建数据</div>';
                return;
            }
            
            const latestBuild = data.recent_builds[0];
            const status = latestBuild[7]; // status字段
            const commitMessage = latestBuild[2] || '无提交信息';
            const author = latestBuild[3] || '未知';
            const startTime = new Date(latestBuild[5]).toLocaleString();
            
            let statusClass = 'status-success';
            let statusText = '构建成功';
            
            if (status === 'FAILED') {
                statusClass = 'status-failed';
                statusText = '构建失败';
            } else if (status === 'BUILDING') {
                statusClass = 'status-building';
                statusText = '构建中...';
            } else if (status === 'ERROR') {
                statusClass = 'status-failed';
                statusText = '构建异常';
            }
            
            statusDiv.innerHTML = `
                <div class="build-item">
                    <div class="build-info">
                        <div class="build-commit">
                            <span class="status-indicator ${statusClass}"></span>
                            ${statusText}
                        </div>
                        <div class="build-meta">
                            ${commitMessage.substring(0, 50)}${commitMessage.length > 50 ? '...' : ''}<br>
                            作者: ${author} | 时间: ${startTime}
                        </div>
                    </div>
                </div>
            `;
        }
        
        // 更新构建统计
        function updateBuildStats(data) {
            if (!data || !data.status_stats) return;
            
            let totalBuilds = 0;
            let successBuilds = 0;
            
            data.status_stats.forEach(([status, count]) => {
                totalBuilds += count;
                if (status === 'SUCCESS') {
                    successBuilds += count;
                }
            });
            
            document.getElementById('total-builds').textContent = totalBuilds;
            document.getElementById('success-rate').textContent = 
                totalBuilds > 0 ? Math.round((successBuilds / totalBuilds) * 100) + '%' : '0%';
            
            // 更新图表
            updateStatusChart(data.status_stats);
        }
        
        // 更新状态图表
        function updateStatusChart(statusStats) {
            const ctx = document.getElementById('statusChart').getContext('2d');
            
            if (statusChart) {
                statusChart.destroy();
            }
            
            const labels = [];
            const data = [];
            const colors = [];
            
            statusStats.forEach(([status, count]) => {
                labels.push(status);
                data.push(count);
                
                switch(status) {
                    case 'SUCCESS':
                        colors.push('#48bb78');
                        break;
                    case 'FAILED':
                        colors.push('#f56565');
                        break;
                    case 'BUILDING':
                        colors.push('#ed8936');
                        break;
                    default:
                        colors.push('#a0aec0');
                }
            });
            
            statusChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: colors,
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
        }
        
        // 更新最近构建列表
        function updateRecentBuilds(data) {
            const buildsDiv = document.getElementById('recent-builds');
            
            if (!data || !data.recent_builds || data.recent_builds.length === 0) {
                buildsDiv.innerHTML = '<div class="error">暂无构建历史</div>';
                return;
            }
            
            const buildsHtml = data.recent_builds.slice(0, 5).map(build => {
                const [id, commitHash, commitMessage, author, branch, startTime, endTime, status, buildLog, duration] = build;
                
                let statusClass = 'status-success';
                if (status === 'FAILED' || status === 'ERROR') statusClass = 'status-failed';
                if (status === 'BUILDING') statusClass = 'status-building';
                
                const shortHash = commitHash ? commitHash.substring(0, 8) : 'N/A';
                const shortMessage = commitMessage ? 
                    (commitMessage.length > 40 ? commitMessage.substring(0, 40) + '...' : commitMessage) : 
                    '无提交信息';
                
                return `
                    <div class="build-item">
                        <div class="build-info">
                            <div class="build-commit">
                                <span class="status-indicator ${statusClass}"></span>
                                #${id} ${shortHash}
                            </div>
                            <div class="build-meta">
                                ${shortMessage}<br>
                                ${author || '未知'} | ${new Date(startTime).toLocaleString()}
                            </div>
                        </div>
                        <div class="build-duration">
                            ${duration ? duration + 's' : '-'}
                        </div>
                    </div>
                `;
            }).join('');
            
            buildsDiv.innerHTML = buildsHtml;
        }
        
        // 更新系统监控（模拟数据）
        function updateSystemMetrics() {
            // 这里可以集成真实的系统监控数据
            document.getElementById('system-cpu').textContent = Math.floor(Math.random() * 30 + 10) + '%';
            document.getElementById('system-memory').textContent = Math.floor(Math.random() * 40 + 30) + '%';
        }
        
        // 主更新函数
        async function updateDashboard() {
            const data = await fetchBuildData();
            
            if (data) {
                updateCurrentStatus(data);
                updateBuildStats(data);
                updateRecentBuilds(data);
            }
            
            updateSystemMetrics();
        }
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            updateDashboard();
            
            // 每30秒自动刷新
            setInterval(updateDashboard, 30000);
        });
    </script>
</body>
</html>
